import React, { useEffect, useState } from "react";
import '../proof.css';
import '../../../App.css'
import '../../Login/login.css';
import { useHistory, useLocation } from "react-router-dom/cjs/react-router-dom";
import { Mask, DotLoading } from "antd-mobile";
import { useDispatch } from "react-redux";
import { isProofContact, isProofFace, isProofFrequentlyUsedApps, isProofMobile } from "@/store/actions/userState";
import { isEmptyString, toTrimString } from "@/utils/utils";
import { PageTag } from "@/utils/pageTag";
import ProofNavigateBar from "@/components/ProofNavigateBar";
import { useFormik } from "formik";
import FormOtpInput from "@/components/FormOtpInput";
import FormMobileInput from "@/components/FormMobileInput";
import { isLoanLoaning, isLoanReject, isLoanRepayNow, isLoanReviewing, isLoanSigning } from "@/utils/loanStatus";
import AddHomeEvent from "@/utils/addHomeEvent";
import PrivacyPolicyLink from "@/components/PrivacyPolicyLink/PrivacyPolicyLink";
import { reqDataSmsCodeLogin, reqSaveEvent, reqSendDataSmsCode, reqUserState } from "@/store/actions/apiServices";

/**
 * 认证号码页
 */
export default function ProofMobile() {

    //loading状态
    const [maskVisible, setMaskVisible] = useState(false)

    //显示add home弹框
    const [addHomeMaskVisible, setAddHomeMaskVisible] = useState(false);
    const [addHomeMaskIsHomeMode, setAddHomeMaskIsHomeMode] = useState(true);

    // 获取路由历史 history 对象
    const history = useHistory()

    // 获取路由信息 location 对象
    const location = useLocation()

    //获取 Redux 分发器
    const dispatch = useDispatch()

    //倒计时状态
    const [canStart, setCanStart] = useState(false);

    //获取Redux Store中的用户状态信息
    const [userStateInfo, setUserStateInfo] = useState({});

    const onReqUserStateCallback = (success, resObj) => {
        setMaskVisible(false);
        if (success && resObj) {
            console.log("Launch-signOrderId: " + resObj.signOrderId);
            setUserStateInfo(resObj);

            //是否为签约中
            const isHomeSigning = isLoanSigning(resObj.signFlag, resObj.signOrderId);
            //是否为审核中
            const isHomeReviewing = isLoanReviewing(resObj.applyStatus);
            //是否为拒绝
            const isHomeReject = isLoanReject(resObj.applyStatus, resObj.orderStatus);
            //是否为放款中
            const isHomeLoaning = isLoanLoaning(resObj.orderStatus);
            //是否为待还款
            const isHomeRepay = isLoanRepayNow(resObj.orderStatus);
            //是否为待进件
            const isHomeNotLoan = ((!isHomeReviewing) && (!isHomeReject) && (!isHomeLoaning) && (!isHomeRepay));
            console.log("Launch-isHomeReviewing: " + isHomeReviewing);
            console.log("Launch-isHomeReject: " + isHomeReject);
            console.log("Launch-isHomeLoaning: " + isHomeLoaning);
            console.log("Launch-isHomeRepay: " + isHomeRepay);
            console.log("Launch-isHomeNotLoan: " + isHomeNotLoan);
            console.log("Launch-isHomeSigning: " + isHomeSigning);

            //跳转状态页
            if (isHomeSigning) {
                history.replace('/guide');
                return;

            } else if (isHomeReviewing) {
                history.replace('/review');
                return;

            } else if (isHomeReject) {
                history.replace('/reject');
                return;

            } else if (isHomeLoaning) {
                history.replace('/loaning');
                return;

            } else if (isHomeRepay) {
                history.replace('/repay');
                return;
            }

            //判断下是否已经做完所有认证
            if (resObj.isProofFinish === true) {
                //跳转申请页
                history.replace('/apply');
                return;
            }

            //是否为号码认证
            if (isProofMobile(resObj.stepTitle)) {
                //跳转申请页
                return;
            }

            //是否为常用app认证
            if (isProofFrequentlyUsedApps(resObj.stepTitle)) {
                //跳转申请页
                history.replace('/prooffrequentlyapps');
                return;
            }

            //是否为人脸认证
            if (isProofFace(resObj.stepTitle)) {
                history.replace('/proofface');
                return;
            }

            if (isProofContact(resObj.stepTitle)) {
                if (window.isSupportContactPicker === true) {
                    history.replace('/proofcontact');
                } else {
                    history.replace('/proofcontactinput');
                }
                return;
            }
            history.replace('/proof');
        }
    };

    // Formik 表单对象
    const form = useFormik({
        //设置表单初始值
        initialValues: {
            mobile: userStateInfo.readonlyMobile,
            code: ""
        },

        //提交
        onSubmit: values => {
            console.log(values)

            //提交登录
            onLoginSubmit()
        },

        //校验
        validate(values) {
            const errors = {}
            if (!values.mobile) {
                errors.mobile = "phone number can't be none"
            }
            if (!values.code) {
                errors.code = "otp can't be none"
            }

            return errors
        }
    })

    const checkUserStateInfo = async () => {
        try {
            setMaskVisible(true);
            reqUserState(PageTag.PROOF_MOBILE, onReqUserStateCallback);

        } catch (e) {
            console.log(e)
        }
    }

    const doSendOtp = async (mobile) => {
        try {
            setMaskVisible(true);
            reqSendDataSmsCode(mobile, (success, resObj) => {
                setMaskVisible(false);

                if (success) {
                    setCanStart(true);
                }
            });

        } catch (e) {
            console.log(e)
        }
    }

    //请求登录接口
    const doOtpLogin = async (mobile, code, orderId = "") => {
        if (isEmptyString(mobile) || isEmptyString(code)) {
            return;
        }

        try {
            setMaskVisible(true)
            reqDataSmsCodeLogin(mobile, code, orderId, (success, resObj) => {
                setMaskVisible(false)
                if (success) {
                    checkUserStateInfo();
                }
            });

        } catch (e) {
            console.log(e)
        }
    }

    //点击获取otp
    const onSendSmsCode = () => {
        reqSaveEvent("PROOF_MOBILE_OTP_CLICK")

        let mobile = toTrimString(form.values.mobile + "")
        if (mobile.length < 9) {
            form.setTouched({ mobile: true })
            return
        }

        doSendOtp(mobile)
    }

    //点击登录
    const onLoginSubmit = () => {
        try {
            reqSaveEvent("PROOF_MOBILE_COMMIT_CLICK");

            let mobile = toTrimString(form.values.mobile + "");
            let code = toTrimString(form.values.code + "");
            let orderId = ""//sendDataSmsCodeInfo.fetchOrderId + ""
            doOtpLogin(mobile, code, orderId);

        } catch (e) {
            console.log(e)
        }
    }

    //点击返回
    const onHandleNavGoBack = () => {
        history.replace('/home');
    }

    // 点击add home监听
    const onHandleAddToHome = (type) => {
        if (type === 'home') {
            AddHomeEvent.onHandleAddHomeEventClick()
        } else {
            AddHomeEvent.onHandleAddFavoriteEventClick()
        }
    }

    // 关闭add home
    const onHandleAddToHomeClose = () => {
        setAddHomeMaskVisible(false)
    }

    useEffect(() => {
        checkUserStateInfo()
        reqSaveEvent("PROOF_MOBILE_START")

        return () => {
            reqSaveEvent("PROOF_MOBILE_END")
        }
    }, [])


    return (
        <div className="proofRoot">
            <ProofNavigateBar theme="white" onBackClick={onHandleNavGoBack} onAddFavorite={() => { setAddHomeMaskIsHomeMode(false); setAddHomeMaskVisible(true) }} onAddHome={() => { setAddHomeMaskIsHomeMode(true); setAddHomeMaskVisible(true) }}>{userStateInfo.pageTitle}</ProofNavigateBar>

            <form className="proofContent" onSubmit={form.handleSubmit}>
                {userStateInfo.readonlyMobile && (userStateInfo.readonlyMobile.length > 0) && <div className="proofItemList">
                    <FormMobileInput
                        name="mobile"
                        placeholder="Enter phone number"
                        value={form.values.mobile}
                        title="Phone number"
                        type="text"
                        readOnly="readOnly"
                        onBlur={form.handleBlur}
                        onChange={form.handleChange}
                        autoComplete="off" />
                </div>}
                {!userStateInfo.readonlyMobile && <div className="proofItemList">
                    <FormMobileInput
                        name="mobile"
                        placeholder="Enter phone number"
                        value={form.values.mobile}
                        title="Phone number"
                        type="text"
                        onBlur={form.handleBlur}
                        onChange={form.handleChange}
                        autoComplete="off" />
                </div>}
                {form.errors.mobile && form.touched.mobile && (
                    <div className="validate contentLeftMargin">{form.errors.mobile}</div>
                )}

                <div className="proofItemList">
                    <FormOtpInput
                        title="Verification code"
                        name="code"
                        placeholder="Enter verification code"
                        type="text"
                        value={form.values.code}
                        onChange={form.handleChange}
                        onBlur={form.handleBlur}
                        onClickCallback={onSendSmsCode}
                        canStart={canStart}
                        autoComplete="off" />
                </div>
                {form.errors.code && form.touched.code && (
                    <div className="validate contentLeftMargin">{form.errors.code}</div>
                )}
            </form>

            <div className="proofOtpTips">{userStateInfo.readonlyMobile ? "MTN" : "We"} will send a OTP to your mobile number. Fill in the OTP to verify the validity of your mobile phone number.</div>

            <div className="proofApplyBtn" onClick={form.handleSubmit}>
                <div className="mainButtonGradient">Next</div>
            </div>

            <PrivacyPolicyLink pageTag={userStateInfo.pageTitle} showCheckbox={false} linkText="Privacy policy" />

            {/* <AddToHomeGifDialog visible={addHomeMaskVisible} onConfirm={onHandleAddToHome} onClose={onHandleAddToHomeClose} isHomeMode={addHomeMaskIsHomeMode} /> */}

            <Mask visible={maskVisible} opacity={0.1}
                onMaskClick={() => { }}>
                <div className="overlayContent">
                    <span style={{ fontSize: 24, color: '#ff3141' }} >
                        <DotLoading color="currentColor" />
                    </span>
                </div>
            </Mask>
        </div>
    )
}